'use strict';
var gulp = require('gulp'),
	browserify = require('browserify'),
	gulpBrowserify = require('gulp-browserify'),
	browserSync = require('browser-sync'),
	// 编译 less 文件
	less = require('gulp-less'),
	// 压缩 css 文件
	minifyCss = require('gulp-minify-css'),
	// gulp watch 执行过程中，如遇异常自动提醒 notify,plumber
	notify = require('gulp-notify'),
	plumber = require('gulp-plumber'),
	// 为各个浏览器自动添加前缀，如 -webkit-transform
	autoprefixer = require('gulp-autoprefixer'),
	// 合并文件
	concat = require('gulp-concat'),
	uglify = require('gulp-uglify'),
	// 给页面的引用添加版本号，清除页面的引用缓存
	rev = require('gulp-rev-append'),
	// 给 CSS 文件中的引用添加版本号
	cssver = require('gulp-make-css-url-version'),
	// 压缩图片文件（jpg,png,svg,gif）
	imagemin = require('gulp-imagemin'),
	// imagemin 的图片深度压缩插件 pngquant
	pngquant = require('imagemin-pngquant'),
	// 缓存文件，如在 imagemin 时，我们只需要压缩修改过的图片而不需要全部重新压缩，就可以使用 cache 方法
	cache = require('gulp-cache'),
	// 压缩 HTML 文件
	htmlmin = require('gulp-htmlmin'),
	// 地图文件，在压缩后的JS文件内增加注释
	sourcemaps = require('gulp-sourcemaps'),
	babel = require('gulp-babel'),
	babelify = require('babelify'),
	reactify = require('reactify'),
	source = require('vinyl-source-stream');

gulp.task('help', function() {
	console.log('gulp build			文件编译打包');
	console.log('gulp dev			测试环境运行');
});



gulp.task('default', function() {
	gulp.start('help');
});

gulp.task('test', ['buildLess']);

gulp.task('buildLess', function() {
	gulp.src('src/less/**/*.less')
	.pipe(plumber({errorHandler: notify.onError('Error: <%=error.message%>')}))
	.pipe(less())
	.pipe(autoprefixer({
		browsers: ['last 2 versions'],
		cascade: true, // 美化属性值
		remove:true // 去除不必要的前缀
	}))
	.pipe(cssver())
	.pipe(minifyCss())
	.pipe(gulp.dest('src/css'));
});

gulp.task('concatJS', function() {
	gulp.src('src/scripts/**/*.js')
		.pipe(sourcemaps.init())
		.pipe(concat('build.js'))
		.pipe(uglify())
		.pipe(sourcemaps.write())
		.pipe(gulp.dest('dist/js'));
});

gulp.task('concatCSS', ['buildLess'], function() {
	gulp.src('src/css/**/*.css')
		.pipe(concat('build.css'))
		.pipe(gulp.dest('dist/css'));
});

gulp.task('testConcat', ['concatCSS', 'concatJS']);

gulp.task('testUglify', function() {
	gulp.src('src/scripts/**/*.js')
		.pipe(uglify())
		.pipe(gulp.dest('dist/js'));
});
	
gulp.task('testRev', function() {
	gulp.src('src/**/*.html')
		.pipe(rev())
		.pipe(gulp.dest('dist'));
});

gulp.task('testImagemin', function() {
	gulp.src('src/images/*.{gif,jpg,png,ico}')
		.pipe(cache(imagemin({
			optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
			progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
			interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
			multipass: true, //类型：Boolean 默认：false 多次优化svg直到完全优化
			use: [pngquant()]
		})))
		.pipe(gulp.dest('dist/images'))
});

gulp.task('testHtmlmin', function() {
	gulp.src('src/**/*.html')
	.pipe(htmlmin({
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    }))
	.pipe(gulp.dest('dist'));
});

gulp.task('testBabel', function() {
	gulp.src('src/scripts/test.js')
		.pipe(browserify({
			debug: true
		}))
		.pipe(sourcemaps.init())
		.pipe(babel())
		.pipe(sourcemaps.write())
		.pipe(gulp.dest('dist/scripts'));
});

gulp.task('testGulpBrowserify', function() {
	gulp.src('src/scripts/app.js')
		.pipe(gulpBrowserify({
			debug: true,
			transform: [reactify]
		}))
		.pipe(gulp.dest('dist/scripts'));
});

gulp.task('testBrowserify', function() {
	return browserify({entries: 'src/scripts/test.js', extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .pipe(source('test.js'))
        .pipe(gulp.dest('dist/scripts'));
});

gulp.task('buildSpaJS', function() {
	return browserify({entries: 'src/scripts/spa.js', extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .pipe(source('spa.js'))
        .pipe(gulp.dest('dist/scripts'));
});

gulp.task('watch', function() {
	gulp.watch('src/less/**/*.less', ['buildLess']);
});

gulp.task('build', ['concatCSS', 'testBrowserify', 'buildSpaJS', 'testHtmlmin']);

gulp.task("dev", function(){
	browserSync({
		notify: false,
		file: '**',
		server: {
			baseDir: 'dist'
		}
	});

	gulp.watch(['*'], {cwd: 'dist'}, browserSync.reload);
});